import 'dart:io';

import 'package:core_package/core_package.dart';
import 'package:core_package/services/delegate/request_delegate.dart';
import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import '../cache/user_info.dart';
import '../log/LogUtil.dart';
import 'config/http_config.dart';
import 'config/http_request_method.dart';

import 'package:package_info/package_info.dart';

class HttpRequest {
  //初始化
  static init({
    required String url,
  }) async {
    HttpConfig.baseURL = url;
    if (Platform.isIOS) {
      model = "iOS";
    } else if (Platform.isAndroid) {
      model = "android";
    }
    _getId().then((value) => deviceID = value);
    _initPackageVersion().then((value) => version = value.version);
  }

  static final BaseOptions _baseOptions = BaseOptions(
    baseUrl: HttpConfig.baseURL, /*connectTimeout: HttpConfig.timeout*/
  );
  static final Dio dio = Dio(_baseOptions);

  static Future<T?> getRequest<T>(
    String url, {
    Map<String, dynamic>? params,
    Interceptor? inter,
    RequestDelegate? delegate,
  }) async {
    return _request(
      url,
      params: params,
      method: HttpRequestMethodType.get,
      inter: inter,
      delegate: delegate,
    );
  }

  static Future<T?> postRequest<T>(
    String url, {
    Map<String, dynamic>? params,
    Interceptor? inter,
    RequestDelegate? delegate,
  }) async {
    return _request(
      url,
      params: params,
      method: HttpRequestMethodType.post,
      inter: inter,
      delegate: delegate,
    );
  }

  static Future<T?> _request<T>(
    String url, {
    HttpRequestMethodType method = HttpRequestMethodType.post,
    Map<String, dynamic>? params,
    Interceptor? inter,
    RequestDelegate? delegate,
  }) async {
    if (params == null) params = {};
    if (UserCacheUil.getInt('USERID') != null) {
      params['userId'] = UserCacheUil.getInt('USERID')??0;
    }
    //创建配置文件
    String methodType = (method == HttpRequestMethodType.get) ? HttpRequestMethod.get : HttpRequestMethod.post;
    final option = Options(
      method: methodType,
      headers: headers,
    );

    //2.1 全局拦截器
    //创建全局默认的全局拦截器
    // Interceptor dInter = InterceptorsWrapper(onRequest: (
    //   options,
    //   handler,
    // ) {
    //   // return options; //请求拦截
    // }, onResponse: (response, handler) {
    //   // return response; // 结果拦截
    // }, onError: (err, handler) {
    //   // return err; // 错误拦截
    // });
    // List<Interceptor> inters = [dInter];
    //
    // // 请求单独拦截器
    // if (inter != null) {
    //   inters.add(inter);
    // }
    // dio.interceptors.addAll(inters);

    //3. 发送网络请求
    try {
      //----防止发送请求异常

      print(" $url 请求参数：\n$params");

      Response response = await dio.request(url,
          data: (method == HttpRequestMethodType.get) ? null : params,
          queryParameters: (method == HttpRequestMethodType.get) ? params : null,
          options: option);

      LogUtil.debug(response);
      // if (response.data["status"] == 1002) {
      //   UserInfoInstance().token = null;
      // }
      return response.data;
    } on DioError catch (e) {
      print('DioError');
      return Future.error(e);
    }
  }

  static Future<T?> upDataImageOrVideo<T>(
    String filePath, {
    bool isVideo = false,
  }) async {
    String url;
    if (isVideo) {
      url = "/uploadVideo";
    } else {
      url = "/upload";
    }
    Map<String, dynamic> map = Map();
    map['file'] = await MultipartFile.fromFile(filePath, filename: "123.jpg");

    FormData formData = FormData.fromMap(map);
    final option = Options(method: HttpRequestMethod.post, headers: headers);
    print(headers);
    print(filePath);
    try {
      Response response =
          await dio.request(url, options: option, data: formData, onSendProgress: (int progress, int total) {
        print("当前进度是$progress  总进度是$total");
      });
      var data = response.data;
      print(data);
      return data;
    } on DioError catch (e) {
      print("出错了");
      return Future.error(e);
    }
  }

  static String? deviceID;
  static String? model;
  static String? version;
  static String? token;

  //请求头部内容
  static Map<String, String?> get headers {
    Map<String, String?> headers = Map<String, String?>();
    headers.addAll({"model": model});
    headers.addAll({"version": version});

    if (UserInfoInstance().token != null) {
      headers.addAll({"token": UserInfoInstance().token});
    }
    headers.addAll({"device": deviceID});
    return headers;
  }

  static Future<String> _getId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isIOS) {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      return iosDeviceInfo.identifierForVendor; // unique ID on iOS
    } else {
      AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
      return androidDeviceInfo.androidId; // unique ID on Android
    }
  }

  static Future<PackageInfo> _initPackageVersion() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    return info;
  }
}
